﻿using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using NUnit.Framework;

using Microsoft.WowAddonStudio.FrameXml.Formats.Blp;

namespace Microsoft.WowAddonStudio.FrameXml.Formats.Tests.Blp
{
    [TestFixture]
    public class BlpImageTest
    {
        private const string blpImagePath = @"Blp\Data\Tirion.blp";
        private const string expectedImagePath = @"Blp\Data\Tirion.png";

        [Test]
        public void BlpLoadFromTest()
        {
            var blpImage = BlpImage.FromFile(blpImagePath);
            var expectedImage = Image.FromFile(expectedImagePath);

            Assert.IsNotNull(blpImage, "LoadFrom returned null.");
            Assert.AreEqual(expectedImage.Width, blpImage.Width, "Image returned has unexpected width." );
            Assert.AreEqual(expectedImage.Height, blpImage.Height, "Image returned has unexpected height.");

            var blpBitmap = blpImage as Bitmap;
            var expectedBitmap = blpImage as Bitmap;

            if (blpBitmap != null && expectedBitmap != null)
            {
                var rectangle = new Rectangle(0, 0, blpBitmap.Width, blpBitmap.Height);

                BitmapData blpData = blpBitmap.LockBits(rectangle, ImageLockMode.ReadOnly, blpBitmap.PixelFormat);
                var dataSize = blpData.Stride * blpData.Height;
                byte[] blpDataBuffer = new byte[dataSize];
                Marshal.Copy(blpData.Scan0, blpDataBuffer, 0, dataSize);
                blpBitmap.UnlockBits(blpData);

                BitmapData expectedData = expectedBitmap.LockBits(rectangle, ImageLockMode.ReadOnly, expectedBitmap.PixelFormat);
                dataSize = blpData.Stride * blpData.Height;
                byte[] expectedDataBuffer = new byte[dataSize];
                Marshal.Copy(expectedData.Scan0, expectedDataBuffer, 0, dataSize);
                expectedBitmap.UnlockBits(expectedData);

                for (int i = 0; i < dataSize; i++)
                {
                    if (blpDataBuffer[i] != expectedDataBuffer[i])
                        Assert.Fail("BLP image does not match reference image.");
                }
            }
        }
    }
}
